const express = require('express');
const cors = require('cors');

const app = express();

// 中间件
app.use(cors());
app.use(express.json());

// 简易请求日志
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next();
});

// 简易内存数据库（仅用于本地开发演示）
const usersDB = [];

// 注册接口
app.post('/api/register', (req, res) => {
  const { username, password } = req.body || {};
  if (!username || !password) {
    return res.status(400).json({ code: 400, message: '请输入用户名和密码' });
  }
  if (usersDB.some(u => u.username === username)) {
    return res.status(400).json({ code: 400, message: '用户名已存在' });
  }
  usersDB.push({ username, password });
  return res.json({ code: 200, message: '注册成功' });
});

// 登录接口
app.post('/api/login', (req, res) => {
  const { username, password } = req.body || {};
  if (!username || !password) {
    return res.status(400).json({ code: 400, message: '请输入用户名和密码' });
  }
  const user = usersDB.find(u => u.username === username && u.password === password);
  if (!user) {
    return res.status(401).json({ code: 401, message: '用户名或密码错误' });
  }
  return res.json({
    code: 200,
    token: `token-${Date.now()}`,
    userInfo: { username }
  });
});

app.get('/', (req, res) => {
  res.send('API OK');
});

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

app.get('/favicon.ico', (req, res) => {
  res.status(204).end();
});

app.use('/.well-known', (req, res) => {
  res.status(204).end();
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`后端API服务已启动: http://localhost:${PORT}`);
});